package com.example.costumview.customview2;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class MyLinLayout extends ViewGroup {

    private int viewGroupWidth = 0;
    private int viewGroupHeight = 0;

    public MyLinLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = 0;
        int height = 0;

        int marginLeft = 0;
        int marginRight = 0;
        int marginTop = 0;
        int marginBottom = 0;

        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            //测量子控件
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);

            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            //获得子控件的高度和宽度
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
            //得到最大宽度，并且累加高度
            width = Math.max(childWidth, width);
            height += childHeight;


            marginLeft = Math.max(0, lp.leftMargin);
            marginRight = Math.max(0, lp.rightMargin);
            marginTop += lp.topMargin;
            marginBottom += lp.bottomMargin;

        }

        viewGroupWidth = width + marginLeft + marginRight;
        viewGroupHeight = height + marginTop + marginBottom;

        setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth : viewGroupWidth,
                (measureHeightMode == MeasureSpec.EXACTLY ? measureHeight : viewGroupHeight));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int top = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);


            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();



            top+=lp.topMargin;

            child.layout(lp.leftMargin, top, lp.leftMargin+child.getMeasuredWidth(), top + child.getMeasuredHeight());
            top += (child.getMeasuredHeight()+lp.bottomMargin);
        }
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
}
